package cn.iocoder.yudao.module.trade.utils;

import cn.iocoder.yudao.framework.security.core.LoginUser;
import cn.iocoder.yudao.module.system.dal.dataobject.permission.RoleDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.permission.PermissionService;
import cn.iocoder.yudao.module.system.service.permission.RoleService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
@Component
public class MerchantUtils {
    @Resource
    private PermissionService permissionService;
    @Resource
    private AdminUserService userService;
    @Resource
    private RoleService roleService;

    public  Long getMerchantId() {
        // 获取当前登录用户
        LoginUser loginUser = getLoginUser();
        AdminUserDO user = userService.getUser(getLoginUserId());
        Long uid = loginUser != null ? loginUser.getId() : null;
        if (user == null) {
            return null;
        }

        // 1.2 获取角色列表
        Set<Long> roleIds = permissionService.getUserRoleIdListByUserId(getLoginUserId());
        List<RoleDO> roles = roleService.getRoleList(roleIds);

        // 标记是否为商户角色
        boolean isMerchant = false;

        // 检查用户是否有 "merchant" 角色
        for (RoleDO role : roles) {
            if ("merchant".equals(role.getCode())) {
                isMerchant = true;
                break;
            }
        }

        // 如果用户是商户，返回其用户ID作为商户ID
        if (isMerchant) {
            return uid;
        }

        return null;
    }
}
